package ldh.serialize.type;

import java.io.IOException;

import ldh.serialize.BinarySerialized;
import ldh.serialize.io.ByteBuf;
import ldh.serialize.util.SerializedUtil;

public class WapSerialized<T> implements BinarySerialized<T> {
	
	private Class<T> clazz;
	
	public WapSerialized(Class<T> clazz) {
		this.clazz = clazz;
	}

	@Override
	public void write(ByteBuf byteBuf, T t) throws IOException {
		if (t == null) {
			SerializedUtil.writeByte(byteBuf, (byte)0);
			return;
		}
		SerializedUtil.writeByte(byteBuf, (byte)1);
		SerializedUtil.toBytes(byteBuf, t);
	}

	@Override
	public T read(ByteBuf in) throws IOException {
		byte isNull = SerializedUtil.readByte(in);
		if (isNull < 1) return null;
		return SerializedUtil.toObject(in, clazz);
	}

	@Override
	public Class<T> getClassType() {
		return clazz;
	}

}
